using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;

namespace PureStateMachine
{
    public abstract class PStateBrain
    {
        public PState CurrentState { get; set; }
        public PDebugSetting DebugSetting { get; set; }

        public PBlackboard Blackboard => _blackboard;
        private PBlackboard _blackboard;

        public event Action<string> OnDebug;
        
        private Dictionary<string, PState> _states;
        private Dictionary<string, Dictionary<string, Action>> _transferMap;
        private bool _first;

        protected PStateBrain()
        {
            _states = new Dictionary<string, PState>();
            _transferMap = new Dictionary<string, Dictionary<string, Action>>();
            _blackboard = new PBlackboard();
            _first = false;

            DebugSetting = new PDebugSetting()
            {
                enable = true,
                updateDisplay = false
            };
        }

        public abstract void Init();

        public void Update()
        {
            if (CurrentState != null)
            {
                if (!_first)
                {
                    _first = true;
                    StateStart(CurrentState);
                }
                StateUpdate(CurrentState);
            }
        }

        public void TransferTo(string targetState)
        {
            if (_states.TryGetValue(targetState, out var target))
            {
                StateEnd(CurrentState);
                if (_transferMap.ContainsKey(CurrentState.Name))
                {
                    _transferMap[CurrentState.Name][targetState]?.Invoke();
                }
                
                if (DebugSetting.enable)
                {
                    SendDebugEvent($"State transfer from {CurrentState.Name} to {targetState}");
                }
                
                CurrentState = target;
                StateStart(target);
            }
            else
            {
                throw new Exception($"{CurrentState.Name}转移到状态{target.Name}失败，没有目标状态");
            }
        }

        protected void RegisterState(PState state)
        {
            if (_states.ContainsKey(state.Name))
            {
                throw new Exception($"已有同名状态{state.Name}");
            }
            else
            {
                _states.Add(state.Name, state);
                GetStateTransfer(state);

                StateInit(state);
            }
        }

        protected void SetCurrentState(String stateName)
        {
            if (_states.TryGetValue(stateName, out var state))
            {
                CurrentState = state;
            }
            else
            {
                throw new Exception($"未找到状态{state.Name}");
            }
        }

        private void GetStateTransfer(PState state)
        {
            Type type = state.GetType();

            foreach (var method in type.GetMethods())
            {
                var transferMethodAttribute = method.GetCustomAttribute<PTransferMethodAttribute>();
                if (transferMethodAttribute != null)
                {
                    var targetState = transferMethodAttribute.TargetStateName;
                    if (method.CreateDelegate(typeof(Action), state) is Action transferAction)
                    {
                        AddTransferMap(state.Name, targetState, transferAction);
                    }
                    else
                    {
                        throw new Exception($"{state.Name}状态中的{method.Name}方法声明不符合Action签名（无返回值无参）");
                    }
                }
            }
        }

        private void AddTransferMap(string start, string end, Action transferAction)
        {
            if (_transferMap.ContainsKey(start))
            {
                _transferMap[start].Add(end, transferAction);
            }
            else
            {
                _transferMap[start] = new Dictionary<string, Action>();
                _transferMap[start].Add(end, transferAction);
            }
        }

        private void StateInit(PState state)
        {
            state.StateInit();
            if (DebugSetting.enable)
            {
                SendDebugEvent($"{state.Name} Init");
            }
        }
        
        private void StateStart(PState state)
        {
            state.StateStart();
            if (DebugSetting.enable)
            {
                SendDebugEvent($"{state.Name} Start");
            }
        }

        private void StateUpdate(PState state)
        {
            state.StateUpdate();
            if (DebugSetting.enable && DebugSetting.updateDisplay)
            {
                SendDebugEvent($"{state.Name} Update");
            }
        }

        private void StateEnd(PState state)
        {
            state.StateEnd();
            if (DebugSetting.enable)
            {
                SendDebugEvent($"{state.Name} End");
            }
        }
        
        private void SendDebugEvent(string message)
        {
            OnDebug?.Invoke(message);
        }
        
        public string GetBrainInfo()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("现有状态：");
            _states.Select(pair => pair.Key).ToList().ForEach(s => stringBuilder.Append($"{s} "));
            stringBuilder.Append("状态迁移：");
            _transferMap.Select(pair => (pair.Key, pair.Value.Keys.ToList())).ToList().ForEach(statePair =>
            {
                stringBuilder.Append($"{statePair.Key}: ");
                statePair.Item2.ForEach(s => stringBuilder.Append($"{s} "));
            });
            return stringBuilder.ToString();
        }
    }

    public struct PDebugSetting
    {
        public bool enable;
        public bool updateDisplay;
    }
}
